from django.views.generic.simple import direct_to_template
from django.shortcuts import render_to_response
from django.contrib import messages
from filters import AuthenticationFitler
from validationutils import ValidationUtils
from appliance.appliancemanager import ApplianceManager
from appliance.commons import executeCommand
import re, time, socket
subnets = ['255.255.255.0','255.0.0.0','254.0.0.0','252.0.0.0','248.0.0.0','240.0.0.0','224.0.0.0','192.0.0.0','128.0.0.0','255.128.0.0','255.192.0.0','255.224.0.0','255.240.0.0','255.248.0.0','255.252.0.0','255.254.0.0','255.255.0.0','255.255.128.0','255.255.192.0','255.255.224.0','255.255.240.0','255.255.248.0','255.255.252.0','255.255.254.0','255.255.255.0','255.255.255.128','255.255.255.192','255.255.255.224','255.255.255.240','255.255.255.248','255.255.255.252']

@AuthenticationFitler
def index(request):
    appmanager = ApplianceManager()
    appInfo = appmanager.getApplianceInfo()
    vlanArr = appInfo['networkInfo']['vlans']
    sroutesArr = appInfo['networkInfo']['sroutes']
    form = appmanager.getDateTimeInfo()
    return direct_to_template(request, 'admin/index.html', extra_context={'appInfo': appInfo,'vlanArr':vlanArr,'sroutesArr':sroutesArr,'menu':'general', 'form':form})

@AuthenticationFitler
def general(request):
    appmanager = ApplianceManager()
    appInfo = appmanager.getApplianceInfo()
    vlanArr = appInfo['networkInfo']['vlans']
    sroutesArr = appInfo['networkInfo']['sroutes']
    form = appmanager.getDateTimeInfo()
    cmd = "service dhcp3-server status"
    res = executeCommand(cmd, [], True)[0]
    cmd1 = " ifconfig eth0 |grep HWaddr | awk '{ print $5 }'"
    cmd2 = " ifconfig eth1 |grep HWaddr | awk '{ print $5 }'"
    external = executeCommand(cmd1, [], True)[1]
    internal = executeCommand(cmd2, [], True)[1]
    up_time = executeCommand("uptime | awk '{print $1 $2 $3 $4 }'", [],True)[1]
    return direct_to_template(request, 'admin/general.html',extra_context={'appInfo': appInfo,'vlanArr':vlanArr,'sroutesArr':sroutesArr,'up_time':up_time,'form':form,'external':external,'internal':internal,'res_dhcp':res,'menu':'general'})

@AuthenticationFitler
def network(request):
    appmanager = ApplianceManager()
    form = appmanager.getNetworkInfo()
    try:
        proxyForm = appmanager.getProxySettings()
    except:
        proxyForm={}
    return render_to_response('admin/network.html',{"form":form,'subnets':subnets,"proxyForm":proxyForm,'menu':'network'})
